import React, { useState } from 'react';
import { Button, Modal } from 'antd';
import TRNotification from '#/utils/notification.js';
import { HttpCode } from '#/utils/contacts.js';
import { IModalType } from '../../type';
import styles from './index.less';

interface IProps {
  /**
   * 标题
   */
  title?: string;
  /**
   * logo
   */
  logo?: string;
  /**
   * 提示语
   */
  hintText?: string;
  /**
   * 类型
   */
  type?: IModalType;
  /**
   * 确认事件
   */
  onPress: (data: Record<string, any>) => void;
  onOk: () => void;
}

const ConfirmModalComponent = (props: IProps) => {
  const { title, logo, hintText, type = IModalType.MODAL, onOk, onPress } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);

  /**
   * 取消按钮
   */
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  const _onOk = async () => {
    setLoading(true);
    const res: any = await onOk();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setVisible(false);
      onPress({ index: 1, status: HttpCode.SUCCES });
    } else {
      setVisible(false);
      onPress({ index: 1, status: HttpCode.FAIL });
    }
  };

  const footerRender = () => {
    if (type === IModalType.MODAL) {
      return [
        <Button key="dtest1" onClick={_onCancel} loading={loading}>
          取消
        </Button>,
        <Button key="dtest2" type="primary" onClick={_onOk} loading={loading}>
          确定
        </Button>,
      ];
    } else if (type === IModalType.CONFIRM) {
      return [
        <Button key="dtest2" type="primary" onClick={_onOk} loading={loading}>
          确定
        </Button>,
      ];
    } else if (type === IModalType.INFO) {
      return null;
    }
  };

  return (
    <Modal
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          {logo && <img src={logo} className={styles.titleLogo} />}
          <span className={styles.title}>{title}</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>{hintText}</div>
    </Modal>
  );
};

class ConfirmModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ConfirmModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ConfirmModal();
